﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace Smart.Admin.Domain.Common
{
    public static class ObjectExtensions
    {
        public static Dictionary<string, object> ObjectToDictionary(this object obj)
        {
            if (obj == null)
                throw new ArgumentNullException(nameof(obj));

            Dictionary<string, object> dictionary = new Dictionary<string, object>();

            // 获取对象的类型
            Type type = obj.GetType();

            // 获取类型的所有公共属性
            PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (PropertyInfo property in properties)
            {
                // 获取属性的名称和值
                string propertyName = property.Name;
                object propertyValue = property.GetValue(obj);

                // 将属性名和属性值加入字典
                dictionary.Add(propertyName, propertyValue);
            }

            return dictionary;
        }
    }
}
